package cn.kailangtu.dataspot.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketService extends Service {
    String TAG = "SOCKET";
    public SocketService() {
    }
    List<SocketContext> socketContainer = new ArrayList<>();
    Socket mSocket = null;



    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(12, notification);


        }


        initServer();


        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        for (int i = 0; i < socketContainer.size(); i++) {
            socketContainer.get(i).close();
        }
       // EventBus.getDefault().unregister(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        }


        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private void initServer(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(3000);
                    Log.d(TAG, "IP:::" +  serverSocket.getInetAddress().toString());
                    while(true){
                        mSocket = serverSocket.accept();

                        Log.d(TAG,mSocket.getInetAddress().getHostAddress());
                        SocketContext context = new SocketContext();
                        context.build(mSocket);
                        socketContainer.add(context);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG,"initServer Err:"+e.getMessage());
                }
            }
        }).start();
    }

    public void sendToAll(byte[] data)
    {
        for (SocketContext context : socketContainer) {
            try {
                context.sendData(data);
            } catch (Exception e) {
                Log.e(TAG, "发送数据失败: " + e.getMessage());
                socketContainer.remove(context); // 移除非活跃连接
            }
        }
    }




}